package com.rd.p2p.mobile;

import java.io.IOException;
import java.io.PrintWriter;
import java.net.URLEncoder;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.apache.commons.lang3.StringUtils;
import org.apache.struts2.ServletActionContext;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;

import com.alibaba.fastjson.serializer.JSONSerializer;
import com.alibaba.fastjson.serializer.SerializeWriter;
import com.foxinmy.weixin4j.mp.api.OauthApi;
import com.opensymphony.xwork2.ActionInvocation;
import com.opensymphony.xwork2.interceptor.AbstractInterceptor;
import com.qdlc.p2p.biz.service.CooperationLoginService;
import com.qdlc.p2p.biz.service.UserIdentifyService;
import com.qdlc.p2p.biz.service.UserService;
import com.qdlc.p2p.common.constant.Constant;
import com.qdlc.p2p.common.constant.CooperationLoginType;
import com.qdlc.p2p.common.exception.UserException;
import com.qdlc.p2p.common.web.filter.SimplePropertyFilter;
import com.qdlc.p2p.dal.dto.CooperationLogin;
import com.qdlc.p2p.dal.dto.User;

/**
 * 
 * 移动端的拦截器，对微信的拦截进行处理
 * 同时保证usercenter必须要登录才能访问
 * 
 * @author wuhuan
 *
 */
public class MobileInterceptor extends AbstractInterceptor {
	private static Logger LOG = LoggerFactory.getLogger(MobileInterceptor.class);
	private static final long serialVersionUID = -6325242223825713011L;
	private static final String HEADER_USER_AGENT = "user-agent";
	private static final String AUTH_WEIXIN = "micromessenger";
	private static final String URI_USERCENTER = "/usercenter/";
	@Autowired
	private CooperationLoginService cooperationLoginService;
	@Resource
	private UserIdentifyService userIdentifyService;
	@Autowired
	private UserService userService;

	@Override
	public String intercept(ActionInvocation invocation) throws Exception {
		HttpServletRequest request = ServletActionContext.getRequest();
		String url = request.getRequestURI();
		// if (isWeiXinRequest(request) && (url.contains("/app/user/doCardSend") || url.contains("/cardsendsuccess")
		// || url.contains("/cardsend"))) {
		// return invocation.invoke();
		// }
		// if ((url.contains("/app/user/doCardSend") || url.contains("/cardsendsuccess") || url.contains("/cardsend")))
		// {
		// return invocation.invoke();
		// }
		// // 临时关闭微信及app接口
		// if ((url.indexOf("/mobile/") > -1) || (url.indexOf("/app/") > -1)) {
		// ServletActionContext.getResponse().sendRedirect("/404.htm");
		// return null;
		// }

		if (url.indexOf("/mobile/") > -1) {
			User user = (User) request.getSession().getAttribute(Constant.SESSION_USER);
			if (user == null) {
				HttpServletResponse response = ServletActionContext.getResponse();
				if (isWeiXinRequest(request)) {// 是微信浏览器
					// request.getSession().setAttribute("openId", "oVG-BuN3ztWaoLPax2WhLTk6z5ag");

					String openId = (String) request.getSession().getAttribute("openId");
					LOG.debug("openId :" + openId);
					if (StringUtils.isBlank(openId)) {// 如果openid是空的 直接获取code
						String codeUrl = new OauthApi().getAuthorizeURL();
						LOG.debug("codeUrl :" + codeUrl);
						response.sendRedirect(codeUrl);
					} else {
						LOG.debug("已經得到openId :" + openId);
						// 如果已经绑定微信,则自动登录
						CooperationLogin cooperationLogin = cooperationLoginService.getCooperationLogin(openId,
								Integer.parseInt(CooperationLoginType.TYPE_WEIXIN));
						if (cooperationLogin != null) {
							User u = userService.find(cooperationLogin.getUserId());
							HttpSession session = request.getSession();
							session.setAttribute(Constant.SESSION_USER, u);
							session.setAttribute(Constant.SESSION_USER_IDENTIFY,
									userIdentifyService.getUserIdentifyByUserId(u.getUserId()));
							session.setAttribute("logintime", new Date().getTime());
						}
					}
				}
				if (request.getRequestURI().indexOf(URI_USERCENTER) > -1) {
					String redirectUrl = request.getRequestURI()
							+ (request.getQueryString() == null ? "" : ("?" + request.getQueryString()));
					response.sendRedirect(request.getContextPath() + "/mobile/user/login.html?redirectURL="
							+ URLEncoder.encode(redirectUrl, "utf-8"));
				}
			}

		}
		if (url.indexOf("/app/") > -1) {
			try {
				return invocation.invoke();
			} catch (UserException e) {
				Map<String, Object> data = new HashMap<String, Object>();
				data.put("resCode", "0");
				data.put("resMsg", e.getMessage());
				printWebJson(getStringOfJpaObj(data));
				return null;
			} catch (Exception e) {
				e.printStackTrace();
				Map<String, Object> data = new HashMap<String, Object>();
				data.put("resCode", "0");
				data.put("resMsg", "服务端产生异常请联系管理员");
				printWebJson(getStringOfJpaObj(data));
				return null;
			}
		}
		return invocation.invoke();
	}

	protected String getStringOfJpaObj(Object obj) {
		SimplePropertyFilter spf = new SimplePropertyFilter();
		SerializeWriter sw = new SerializeWriter();
		JSONSerializer serializer = new JSONSerializer(sw);
		serializer.getPropertyFilters().add(spf);
		serializer.write(obj);
		return sw.toString();
	}

	protected void printWebJson(Object json) throws IOException {
		HttpServletResponse response = ServletActionContext.getResponse();
		response.setContentType("application/json;charset=UTF-8");
		PrintWriter out = response.getWriter();
		out.print(json);
		out.flush();
		out.close();
	}

	/**
	 * 判断请求是否来自微信服务器
	 */
	public static boolean isWeiXinRequest(HttpServletRequest request) {
		String userAgent = request.getHeader(HEADER_USER_AGENT).toLowerCase();
		return userAgent.indexOf(AUTH_WEIXIN) > 0;
	}

}
